<template>
	<input ref="inputRef" v-model="modelValue" min="0000" max="9999" @focus="onFocus" @input="input"
		:disabled="!editable" class="input-box" />
</template>

<script lang="ts" setup>
import { reactive, shallowRef, watch, onBeforeUnmount, ref, computed } from 'vue';
import { useVModel } from '@vueuse/core'
import { clog, isNull } from '/@/utils';

const props = defineProps({
	modelValue: {
		type: String, default: ''
	},
	length: {
		type: Number,
		default: 2
	},
	min: {
		type: Number,
		default: 0
	},
	max: {
		type: Number,
		default: 3000
	}, editable: {
		type: Boolean,
		default: true
	},
})
const emit = defineEmits(['update:modelValue', "onOK"])
const modelValue = useVModel(props, 'modelValue', emit)
const inputRef = ref();

//事件
const onFocus = (e: any) => {
	e.target.select();
}

const input = () => {
	// a, 值预处理
	var mv = `${inputRef.value.value}`
	mv = removeNonDigits(mv); //1,去掉非数字字符, emit('update:foo', 'foo')
	if (len(mv) > props.length) {
		mv = mv.slice(-props.length);  //2,按长度从尾部截取
	}
	modelValue.value = mv
	// b, 校验值是否合法
	if (len(mv) == props.length) {
		var year = toInt(mv);
		if (year < props.min || year > props.max) {
			inputRef.value.select();
			return;
		} else {
			emit('onOK')
		}
	}
}

//外部方法
const focus = () => {
	inputRef?.value?.focus();
	inputRef?.value?.select();
}

const select = () => {
	inputRef?.value?.select();
}

function removeNonDigits(str: string) {
	return str.replace(/\D/g, '');
}

const len = (val: string) => {
	var str: string = `${val}`;
	if (isNull(str)) {
		return 0
	} else {
		return str.length
	}
}

const toInt = (val: string) => {
	const num = parseInt(val, 10);
	return num;
}

defineExpose({ focus, select })

</script>

<style lang="scss" scoped>
.input-box {
	font-size: 0.9rem;
	flex: 1;
	min-width: 0;
	text-align: center;
	border: 0px solid #ccc;
	color: var(--mk-text-color);
	background-color: transparent;
	/* 允许输入框缩小到0 */
	/* 所有输入框平均分配父div的宽度 */
	/* 如果需要按照固定比例分配，可以设置flex属性为具体的数值，例如flex: 2; */
	/* 也可以通过border和padding等属性调整输入框的样式 */
}
</style>